import member from '@src/store/member'
import base from '@src/store/base'
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { getUrlQueryString } from "@src/common/utils";
import { getCategoryAvailable } from "@src/api/member";
import { parseOpenCardGift } from "@src/common/memberCardUtils";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: member,
    fields: ['isMember', 'categoryImage', 'name', 'cardOrder'],
    actions: ['getBaseInfo'],
  }, {
    store: base,
    fields: ['isInit', 'themeCode', 'splashScreen', 'businessName', 'businessLogo'],
    actions: {
      getThemeConfig: 'themeConfig',
      initReady: 'initReady',
      setIndexPageScene: 'setIndexPageScene'
    }
  }],
  data: {
    cardImg: '/wxapp/static/index/i-ka.png',
    shareImg: '',
    availableData: null,
    shareTitle: '邀请你注册成为会员',
    loading: true,
    navLoading: false,
    login: false,
    setTimeObj: null
  },
  observers: {
    'isInit': function (isInit) {
      console.log('this.data.isInit', this.data.isInit)
      console.log('isInit', isInit)
      if (isInit) {
        this.getTabBar().show();
      } else {
        this.getTabBar().hide();
      }
    },
    'availableData, isMember': function (availableData, isMember) {
      if (availableData == null || availableData.length === 0) {
        return;
      }
      let card = availableData[0];
      if (isMember && this.data.cardOrder != null) {
        for (let item of availableData) {
          if (item.category.cardOrder === this.data.cardOrder) {
            card = item;
            break;
          }
        }
      }
      let category = card.category;
      let openCardGift = parseOpenCardGift(category, card.openCardCouponAward);
      let shareTitle = "";
      openCardGift.forEach(value => {
        shareTitle += `送${value.title}${value.value}${value.aFix},`;
      });
      shareTitle = shareTitle.substring(0, shareTitle.length - 1);
      shareTitle = `邀请你注册成为${category.categoryName}会员,` + shareTitle;
      this.setData({ shareTitle })
    }
  },
  methods: {
    onLoad(options) {
      this.getTabBar().select("indexPage")
      if (this.data.isInit) {
        console.log("进这个isInit")
        setTimeout(() => {
          this.initReady();
        }, 100000)
      }
      let scene = "";
      let receiveWay = "";
      if (options && options.scene) {
        if (decodeURIComponent(options.scene) && !options.receiveWay) {
          scene = decodeURIComponent(options.scene);
        } else if (options.receiveWay) {
          // 微信分享
          scene = options.scene;
          receiveWay = options.receiveWay;
        } else if (options.path) {
          // 线下
          scene = getUrlQueryString("scene")
        }
      }
      this.setIndexPageScene(scene, receiveWay);
    },
    onShareAppMessage() {
      return {
        title: this.data.shareTitle,
        path: `pages/index/main`,
        desc: "",
        imageUrl: this.data.shareImg
      };
    },
    onPullDownRefresh() {
      this.setData({ navLoading: true })
      this.getThemeConfig();
      if (this.data.login) {
        this.getBaseInfo();
      }

      this.selectComponent('#promotionTheme').openRecommendService()
      setTimeout(() => {
        this.setData({ navLoading: false })
        wx.stopPullDownRefresh();
      }, 300)
    },
    onLogin() {
      this.fetchData();
      this.setData({ loading: false, login: true });
    },
    onAnon() {
      this.fetchData();
      this.setData({ loading: false, login: false })
    },
    onShow() {
      console.log(' this.selectComponent', this.selectComponent('#promotionTheme'));
      let self = this;
      if (self.selectComponent('#promotionTheme') == null) {
        let setTimeObj = setTimeout(() => {
          self.getPromotionThemeObj();
        }, 1000);
        this.setData({
          setTimeObj
        })
      } else { self.getPromotionThemeObj(); }
    },
    getPromotionThemeObj() {
      if (this.selectComponent('#promotionTheme')) {
        console
        this.setData({
          setTimeObj: null
        })
        this.selectComponent('#promotionTheme').openRecommendService()
      }
    },
    fetchData() {
      getCategoryAvailable().then(res => {
        const availableData = res.data;
        if (availableData && availableData.length > 0) {
          this.setData({ availableData: availableData, 'cardImg': availableData[0].category.cardImage })
        } else {
          this.setData({ availableData: [], 'cardImg': '/wxapp/static/index/i-ka.png' })
        }
      }).catch((e) => {
        this.setData({ availableData: [], 'cardImg': '/wxapp/static/index/i-ka.png' })
      })
    },
    handlePoster(e) {
      this.setData({ "shareImg": e.detail })
    },
    handleLogin() {
      const loginComp = this.selectComponent("#login");
      loginComp.requireLogin();
    },
  }
})
